from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import argparse


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('keywords', nargs='+')
    parser.add_argument('-e', '--extensions', nargs='+')
    parser.add_argument('-d', '--directory', nargs='?')
    return parser.parse_args()


class ExtensionTester(object):
    def __init__(self, extFlag):
        self.extensions = (extFlag or self.open_extensions_file())
        self.extensions = [(('.' + e) if (e != '') else e) for e in self.extensions]


    def test(self, filename):
        extension = os.path.splitext(filename)[1]
        return (extension.lower() in self.extensions)


    def open_extensions_file(self):
        return [ext.strip('\n') for ext in open('extensions.txt')]


class FileTester(object):
    def __init__(self, keywords, case_sensitive):
        self.keywords = keywords
        self.case_sensitive = case_sensitive


    def test(self, filename):
        linelist = [line.strip('\n') for line in open(filename)]

        for keyword in self.keywords:
            found = False
            for line in linelist:
                if not self.case_sensitive:
                    key = keyword.lower()
                    text = line.lower()
                else:
                    key = keyword
                    text = line
                if key in text:
                    print ("Found " + keyword + ", in: " + filename + ", at: " + line)
                    return True
        return False


def test_filename(keywords, filename):
    for keyword in keywords:
        if (keyword in filename):
            return True
        return False

if (__name__ == '__main__'):
    flags = parse_args()
    extTester = ExtensionTester(flags.extensions)
    fileTeste = FileTester(flags.keywords, False)
    print('Searching for {} in files with these extensions:'.format(flags.keywords), extTester.extensions)
    print('Root directory: {}'.format((flags.directory or os.getcwd())), '\n')
    filenames = []
    for (dirpath, subdirs, files) in os.walk((flags.directory or os.getcwd())):
        for x in files:
            try:
                if(extTester.test(x) and (fileTeste.test(os.path.join(dirpath, x)) or test_filename(flags.keywords, x))):
                    filenames.append(os.path.join(dirpath, x))
                    print(os.path.join(dirpath, x))
            except UnicodeDecodeError:
                pass
    print('\n{} results.'.format(len(filenames)))
